<script lang="ts" setup>
import { ref, watch, watchEffect, onMounted } from 'vue'
import { Addquestion, getById, updateQuestion } from '@/api/question'
import { useRouter, useRoute } from 'vue-router'
import { categoryList } from '@/api/category'

const questionType = ref([
  { typeName: '单选题', typeNum: 4 },
  { typeName: '多选题', typeNum: 5 },
  { typeName: '判断题', typeNum: 2 },
  { typeName: '简答题', typeNum: 1 }
])

const category = ref([]) //题目分类下拉列表
const categoryByList = async () => {
  //获取题目分类下拉列表
  const res = await categoryList()
  category.value = res.data.data
}
//选项ABCD
const labels = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G'])

const route = useRoute()
let routerId = ref(1)

const getByQuestions = async (id: number) => {
  // const id = Number(route.query.id) //修改跳转传入的id
  console.log('修改传入id', id)
  const res = await getById(id)

  questionFrom.value = res.data.data
  console.log('哈哈哈哈', questionFrom.value)

  //获取题目正确答案下标
  if (questionFrom.value.questionType === '多选题') {
    for (let i = 0; i < questionFrom.value.questionOptions.length; i++) {
      if (questionFrom.value.questionOptions[i].isCorrect === 1) {
        checkList.value.push(i)
      }
    }
  } else {
    for (let i = 0; i < questionFrom.value.questionOptions.length; i++) {
      if (questionFrom.value.questionOptions[i].isCorrect === 1) {
        right.value = i
      }
    }
  }
}
onMounted(() => {
  categoryByList()
})
// 监听路由参数变化，当参数变化时重新执行 getByQuestions
watchEffect(() => {
  const id = route.query.id
  // console.log('hgsriktgder', id)
  if (id !== null && typeof id === 'string' && !isNaN(Number(id))) {
    routerId.value = 2
    // console.log('routerId', routerId.value)
    getByQuestions(Number(id))
  } else if (routerId.value != 1) {
    // console.log('kkkkkk', route.path)
    routerId.value = 1
    questionFrom.value = {
      categoryId: 1, //题目分类id
      questionOptions: Array.from({ length: num.value }, () => ({
        isCorrect: 0,
        optionContent: ''
      })),
      questionType: radio, //题型
      tags: '', //标签
      title: '' //标题
    }
  }
})

const router = useRouter()
const radio = ref('单选题')

const num = ref(4) //选项数量
const right = ref(1) //正确答案选项下标
const checkList = ref<number[]>([]) //多选题答案数组
//构造新增试题对象
const questionFrom = ref({
  categoryId: 1, //题目分类id
  questionOptions: Array.from({ length: num.value }, () => ({
    isCorrect: 0,
    optionContent: ''
  })),
  questionType: radio, //题型
  tags: '', //标签
  title: '' //标题
})
//监听num数量变化
watch(num, (newValue, oldValue) => {
  if (newValue > oldValue) {
    while (questionFrom.value.questionOptions.length < newValue) {
      questionFrom.value.questionOptions.push({
        isCorrect: 0,
        optionContent: ''
      })
    }
  } else {
    questionFrom.value.questionOptions.length = newValue
  }
})
// onMounted(() => {
//     num.value = 4
// })
//新增试题
const Add = async () => {
  console.log('打印多选参数', checkList.value)
  if (radio.value == '多选题')
    for (let i = 0; i < checkList.value.length; i++) {
      let ggg: number = checkList.value[i]
      questionFrom.value.questionOptions[ggg].isCorrect = 1
      console.log('dddd', questionFrom.value.questionOptions)
    }
  else {
    questionFrom.value.questionOptions[right.value].isCorrect = 1
  }

  console.log('打印新增参数', questionFrom.value.questionOptions)
  await Addquestion(questionFrom.value)
  //清空试题
  questionFrom.value = {
    categoryId: 1, //题目分类id
    questionOptions: Array.from({ length: num.value }, () => ({
      isCorrect: 0,
      optionContent: ''
    })),
    questionType: radio, //题型
    tags: '', //标签
    title: '' //标题
  }
  ElMessage.success('新增成功')
  router.push('/article/question') //返回试题列表
}

//修改试题
const update = async () => {
  //重置所有题型答案
  questionFrom.value.questionOptions.forEach((option) => (option.isCorrect = 0))
  //判断是否多选题
  if (questionFrom.value.questionType === '多选题') {
    checkList.value.forEach((index) => {
      questionFrom.value.questionOptions[index].isCorrect = 1
    })
  } else {
    questionFrom.value.questionOptions[right.value].isCorrect = 1
  }
  await updateQuestion(questionFrom.value)
  ElMessage.success('修改成功')
  router.push('/article/question') //返回试题列表
}
</script>

<template>
  <el-card style="height: 86vh">
    <template #header>
      <span style="font-weight: bold; font-size: 20px" v-if="routerId == 1">新增试题</span>
      <span style="font-weight: bold; font-size: 20px" v-else>修改试题</span>
    </template>

    <div style="display: flex; justify-content: space-between">
      <div style="display: flex; flex-direction: column; width: 130px">
        <span style="margin-bottom: 10px; font-weight: bold; font-size: 16px">试题题型</span>

        <!-- 判断是否新增 -->
        <el-radio-group v-model="radio" style="display: flex; flex-direction: column" v-if="routerId == 1">
          <el-radio :value="item.typeName" @click="num = item.typeNum" v-for="(item, i) in questionType" :key="i">{{
            item.typeName
          }}</el-radio>

          <br />
        </el-radio-group>

        <!-- 修改 -->
        <el-radio-group v-if="routerId === 2">
          <el-radio>{{ questionFrom.questionType }}</el-radio>
        </el-radio-group>
      </div>

      <el-scrollbar height="500px" style="width: 100%; margin-left: 60px; display: flex; flex-direction: column">
        <!-- <p v-for="item in 20" :key="item">{{ item }}</p> -->
        <div class="group-title">
          <span v-if="routerId === 1">{{ radio }} - 试题题干</span>
          <span v-else>{{ questionFrom.questionType }} - 试题题干</span>
          <div style="margin-top: 20px">
            <el-input v-model="questionFrom.title" placeholder="请输入标题" type="textarea" />
          </div>
        </div>

        <div class="group-title">
          <span>答案选项</span>
          <div style="margin-top: 20px" v-for="(item, i) in questionFrom.questionOptions" :key="i">
            <p>选项{{ labels[i] }}</p>
            <el-input v-model="questionFrom.questionOptions[i].optionContent" type="textarea" />
          </div>

          <!-- 题目分类下拉列表 -->
          <div style="margin-top: 20px">
            <label>题目分类：</label>
            <el-select
              v-model="questionFrom.categoryId"
              style="width: 24%"
              placeholder="请选择"
              clearable
              @clear="init"
            >
              <el-option v-for="cat in category" :key="cat.id" :label="cat.typeName" :value="cat.id" />
            </el-select>
          </div>

          <p style="color: brown">正确答案：</p>

          <!-- 新增多选 -->
          <el-checkbox-group v-model="checkList" v-if="radio === '多选题'">
            <div v-for="(item, i) in questionFrom.questionOptions" :key="i" style="display: flex; flex-wrap: nowrap">
              <el-checkbox :label="'选项 ' + labels[i]" :value="i" size="large" border />
            </div>
          </el-checkbox-group>

          <!-- 修改多选 -->
          <el-checkbox-group v-model="checkList" v-if="questionFrom.questionType === '多选题'">
            <div v-for="(item, i) in 5" :key="i" style="display: flex; flex-wrap: nowrap">
              <el-checkbox :label="'选项 ' + labels[i]" :value="i" size="large" border />
            </div>
          </el-checkbox-group>

          <el-radio-group v-model="right" v-else>
            <div v-for="(item, i) in questionFrom.questionOptions" :key="i">
              <el-radio :value="i" size="large" border>选项 {{ labels[i] }}</el-radio>
            </div>

            <!-- <el-radio value="2" size="large">Option 2</el-radio> -->
          </el-radio-group>
          <br />

          <el-button type="primary" @click="Add()" style="margin: 20px 0" v-if="routerId == 1">保存</el-button>
          <el-button type="primary" @click="update()" style="margin: 20px 0" v-else>修改</el-button>
        </div>
      </el-scrollbar>
    </div>
  </el-card>
</template>
<style>
.el-radio-group {
  margin-top: 10px;
}

.el-radio {
  width: 130px;
  height: 50px;
  padding-left: 20px;
  margin-bottom: 8px;
  /* border: 1px solid red; */
}

.el-radio.is-checked {
  font-weight: bold;
  background-color: #f5fbff;
  /* 设置选中时的背景色 */
}

.group-title {
  position: relative;
  display: inline-block;
  margin-bottom: 24px;
  font-size: 16px;
  font-weight: 700;
  color: #333333;
  text-indent: 12px;
}

.group-title::before {
  content: '';
  position: absolute;
  top: 12px;
  left: 0;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #36aafd !important;
  border-radius: 2px !important;
}

.el-textarea__inner {
  width: 700px;
  height: 150px;
}
</style>
